<?php

namespace app\models;

use app\librarys\Inteface;
use Yii;

/**
 * 前台商城
 * Class Mall
 * @package app\models
 */
class Mall
{
    const SessionKey_CurrentDomain = 'current_domain';
    const SessionKey_CurrentInstitution = 'current_institution';
    const SessionKey_CurrentUser = 'current_user';
    const SessionKey_CurrentUserTemp = 'current_user_temp';
    const SessionKey_IsFromDomain = 'is_from_domain';  // 当前session中的机构信息是通过domain来的(true),还是通过institution_code来的(false)
    const SessionKey_WeixinOpenid = 'weixin_openid';
    const SessionKey_WeixinNickname = 'weixin_nickname';
    const SessionKey_WeixinHeader = 'weixin_header';
    const SessionKey_Card = 'current_card';
    const SessionKey_CurrentVoucher = 'current_voucher';

    const SessionKey_WeixinLoginPhone = 'weixin_login_phone';

    public static function setCurrentInstitutionByCode($institutionCode)
    {
        $institutionDomain = explode('://', \Yii::$app->request->hostInfo)[1];
        $currentInstitution = Institution::getInstitutionByCode($institutionCode);
        if ($currentInstitution != null) {
            \Yii::$app->session->set(self::SessionKey_CurrentInstitution, $currentInstitution);
            self::_setCurrentDomain($institutionDomain);
            \Yii::$app->session->set(self::SessionKey_IsFromDomain, false);
        }
    }

    public static function setCurrentInstitution()
    {
        $institutionDomain = explode('://', \Yii::$app->request->hostInfo)[1];
        $currentDomain = self::_getCurrentDomain();
        if ($institutionDomain != $currentDomain) {
            self::_setCurrentInstitution($institutionDomain);
        } else {
            $currentInstitution = \Yii::$app->session->get(self::SessionKey_CurrentInstitution);
            if ($currentInstitution == null) {
                self::_setCurrentInstitution($institutionDomain);
            } else {
                $isFromDomain = \Yii::$app->session->get(self::SessionKey_IsFromDomain, false);
                if ($isFromDomain == false) {
                    $institutionCode = \Yii::$app->request->get('institution_code');
                    if (isset($institutionCode)) {
                        if ($institutionCode != $currentInstitution['code']) {
                            self::_setCurrentInstitution($institutionDomain);
                        }
                    }
                }
            }
        }

//        if ($institutionDomain != $currentDomain) {
//            \Yii::$app->session->remove(self::SessionKey_CurrentInstitution);
//            $currentInstitution = Institution::getInstitutionByDomain($institutionDomain);
//            var_dump($currentInstitution);
//            if ($currentInstitution != null) {
//                \Yii::$app->session->set(self::SessionKey_CurrentInstitution, $currentInstitution);
//                self::_setCurrentDomain($institutionDomain);
//            }
//        }
//
//        $currentInstitution = \Yii::$app->session->get(self::SessionKey_CurrentInstitution);
//        if ($currentInstitution != null) {
//            $institutionCode = \Yii::$app->request->get('institution_code');
//            if (isset($institutionCode)) {
//                if ($institutionCode != $currentInstitution['code']) {
//                    $currentInstitution = null;
////                    \Yii::$app->session->remove(self::SessionKey_CurrentInstitution);
////                    \Yii::$app->session->remove(self::SessionKey_CurrentDomain);
//                    \Yii::$app->session->removeAll();
//                }
//            }
//        }
//
//        if ($currentInstitution == null) {
//            $institutionCode = \Yii::$app->request->get('institution_code', ' ');
//            $currentInstitution = Institution::getInstitutionByCode($institutionCode);
//            if ($currentInstitution != null) {
//                \Yii::$app->session->set(self::SessionKey_CurrentInstitution, $currentInstitution);
//                self::_setCurrentDomain($institutionDomain);
//            }
//        }
    }

    private static function _setCurrentInstitution($institutionDomain)
    {
        \Yii::$app->session->remove(self::SessionKey_CurrentInstitution);
        \Yii::$app->session->remove(self::SessionKey_CurrentDomain);
        \Yii::$app->session->remove(self::SessionKey_IsFromDomain);
        \Yii::$app->session->remove(self::SessionKey_CurrentUser);
//        \Yii::$app->session->removeAll();

        $currentInstitution = Institution::getInstitutionByDomain($institutionDomain);
        if ($currentInstitution != null) {
            \Yii::$app->session->set(self::SessionKey_CurrentInstitution, $currentInstitution);
            self::_setCurrentDomain($institutionDomain);
            \Yii::$app->session->set(self::SessionKey_IsFromDomain, true);
        } else {
            $institutionCode = \Yii::$app->request->get('institution_code', ' ');
            $currentInstitution = Institution::getInstitutionByCode($institutionCode);
            if ($currentInstitution != null) {
                \Yii::$app->session->set(self::SessionKey_CurrentInstitution, $currentInstitution);
                self::_setCurrentDomain($institutionDomain);
                \Yii::$app->session->set(self::SessionKey_IsFromDomain, false);
            }
        }
    }

    private static function _setCurrentDomain($domain)
    {
        \Yii::$app->session->set(self::SessionKey_CurrentDomain, $domain);
    }

    private static function _getCurrentDomain()
    {
        return \Yii::$app->session->get(self::SessionKey_CurrentDomain);
    }

    public static function getCurrentInstitution()
    {
        $item = \Yii::$app->session->get(self::SessionKey_CurrentInstitution);
        if ($item == null) {
            throw new \Exception('机构信息为空');
        }

        return $item;
    }

    public static function getCurrentInstitutionName()
    {
        $item = self::getCurrentInstitution();
        return $item['name'];
    }

    public static function getCurrentInstitutionCode()
    {
        $item = self::getCurrentInstitution();
        return $item['code'];
    }

    public static function getCurrentInstitutionIntegralUnit()
    {
        $item = self::getCurrentInstitution();
        return $item['integral_unit'];
    }

    public static function getCurrentInstitutionIntegralRate()
    {
        $item = self::getCurrentInstitution();
        return $item['integral_rate'];
    }

    public static function getCurrentInstitutionIsCashOrder()
    {
        $item = self::getCurrentInstitution();
        return $item['is_cash_order'];
    }

    public static function getCurrentInstitutionSiteName()
    {
        $item = self::getCurrentInstitution();
        return $item['site_name'];
    }


    public static function getCurrentUser()
    {
        $user = \Yii::$app->session->get(self::SessionKey_CurrentUser);
//        if ($user == null) {
//            throw new \Exception('user is not logon!');
//        }
        return $user;
    }

    public static function getCurrentUserTicket()
    {
        $user = self::getCurrentUser();
        if ($user == null) {
            return null;
        }
        return $user['ticket'];
    }

    public static function getCurrentUserId()
    {
        $user = self::getCurrentUser();
        if ($user == null) {
            return null;
        }
        return $user['id'];
//        return '2948fbb4-6a9e-11e6-b3b9-52540014b32f';
    }

    public static function getCurrentUserName()
    {
        $user = self::getCurrentUser();
        if ($user == null) {
            return null;
        }
        return $user['name'];
    }


    public static function setCurrentUser($user)
    {
        \Yii::$app->session->set(self::SessionKey_CurrentUser, $user);
    }

    public static function removeCurrentUser()
    {
        \Yii::$app->session->remove(self::SessionKey_CurrentUser);
    }

    public static function setCurrentUserTemp($user)
    {
        \Yii::$app->session->set(self::SessionKey_CurrentUserTemp, $user);
    }

    public static function getCurrentUserTemp()
    {
        return \Yii::$app->session->get(self::SessionKey_CurrentUserTemp);
    }

    public static function removeCurrentUserTemp()
    {
        \Yii::$app->session->remove(self::SessionKey_CurrentUserTemp);
    }

    public static function userLogout()
    {
        \Yii::$app->session->remove(self::SessionKey_CurrentUser);
    }

    public static function authWeixinUserInfo()
    {
        //判断是否在微信内
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger")) {
            if (empty(self::getWeixinOpenid())) {
                $re = require_once("../librarys/weixinpay/weixin_auth_default.php");
                self::setWeixinOpenid($re['openid']);
                self::setWeixinNickname($re['nickname']);
                self::setWeixinHeader($re['headimgurl']);
                //移除state
                $url = Yii::$app->request->absoluteUrl;
                $url = str_replace('&duolastate=dorabox_weixin_ih_web_auth', '', $url);
                header("Location: $url");
                exit();
            }
        }
    }

    public static function getWeixinOpenid()
    {
        return \Yii::$app->session->get(self::SessionKey_WeixinOpenid);
//        return '1111111111';
    }

    private static function setWeixinOpenid($openid)
    {
        \Yii::$app->session->set(self::SessionKey_WeixinOpenid, $openid);
    }

    public static function getWeixinNickname()
    {
        return \Yii::$app->session->get(self::SessionKey_WeixinNickname);
//        return '2222222222';
    }

    public static function setWeixinNickname($nickname)
    {
        \Yii::$app->session->set(self::SessionKey_WeixinNickname, $nickname);
    }

    public static function getWeixinHeader()
    {
        return \Yii::$app->session->get(self::SessionKey_WeixinHeader);
//        return '';
    }

    public static function setWeixinHeader($header)
    {
        \Yii::$app->session->set(self::SessionKey_WeixinHeader, $header);
    }

    public static function setCurrentCard($card)
    {
        \Yii::$app->session->set(self::SessionKey_Card, $card);
    }

    public static function getCurrentCard()
    {
        return \Yii::$app->session->get(self::SessionKey_Card);
    }

    public static function removeCurrentCard()
    {
        \Yii::$app->session->remove(self::SessionKey_Card);
    }

    public static function setCurrentVoucher($voucher)
    {
        \Yii::$app->session->set(self::SessionKey_CurrentVoucher, $voucher);
    }

    public static function getCurrentVoucher()
    {
        return \Yii::$app->session->get(self::SessionKey_CurrentVoucher);
    }

    public static function removeCurrentVoucher()
    {
        \Yii::$app->session->remove(self::SessionKey_CurrentVoucher);
    }


    public static function setWeixinLoginPhone($phone)
    {
        \Yii::$app->session->set(self::SessionKey_WeixinLoginPhone, $phone);
    }

    public static function getWeixinLoginPhone()
    {
        return \Yii::$app->session->get(self::SessionKey_WeixinLoginPhone);
    }

    public static function removeWeixinLoginPhone()
    {
        \Yii::$app->session->remove(self::SessionKey_WeixinLoginPhone);
    }

    public static function weixinLogin($remark = '')
    {
        $openid = Mall::getWeixinOpenid();
        $nickname = Mall::getWeixinNickname();
        $header = Mall::getWeixinHeader();
        $phone = Mall::getWeixinLoginPhone();
        $data = [
            'id' => '0',
            'code' => '',
            'name' => $nickname,
            'institution_code' => Mall::getCurrentInstitutionCode(),
            'phone' => $phone,
            'isEnabled' => 1,
            'remark' => $remark,
            'wx_openid' => $openid,
            'header_url' => $header
        ];
        $userId = User::addUser($data)['userId'];
        $user = User::getUser($userId);
        Mall::setCurrentUser($user);
    }

    /**
     * 申请开通机构
     * @param $applyData
     * @throws \Exception
     */
    public static function applyForInstitution(&$applyData, &$message, $type)
    {
        $result = true;
        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();
        $institutionCode = '';
        try {
            $data = [
                'code' => '',
                'parentCode' => $applyData['parentCode'],
                'name' => $applyData['txtName'],
                'address' => $applyData['txtAddress'],
                'isEnabled' => 1,
                'isAutoOrder' => 1,
                'isCashOrder' => 1,
                'isAllowImportOrder' => 1,
                'billModel' => 1,
                'integralRate' => 1,
                'integralUnit' => '积分',
                'remark' => '申请开通机构',
                'siteName' => $applyData['txtName'] . '积分商城',
                'domain' => null,
                'themePc' => '',
                'themeM' => '',
                'salesmanName' => '',
                'salesmanPhone' => ''
            ];
            $institutionCode = Institution::addInstitution($data, $message);
            if ($institutionCode == null) {
//                $message = '获取机构编码错误';
                $transaction->rollBack();
                return false;
            }
            $applyData['institution_code'] = $institutionCode;
            // 创建机构联系人
            $data = [
                'code' => $institutionCode,
                'id' => '0',
                'name' => $applyData['txtContacter'],
                'phone' => $applyData['txtContacterPhone'],
                'email' => isset($applyData['txtEmail']) ? $applyData['txtEmail'] : '',
                'remark' => '',
                'isDelete' => 0
            ];
            Institution::manageInstitutionContacter($data);
            //创建用户
            $userData = [];
            $userData['id'] = 0;
            $userData['code'] = 0;
            $userData['name'] = $applyData['txtContacter'];
            $userData['institution_code'] = $applyData['institution_code'];
            $userData['phone'] = $applyData['txtContacterPhone'];
            $userData['remark'] = '申请开通机构';
            $userData['isEnabled'] = 1;
            $userData['wx_openid'] = '';
            $userData['header_url'] = '';
            User::addUser($userData);

            Goods::sysHigherInstGoodsCategory($institutionCode);  // 同步机构商品分类
            Goods::sysHigherInstgoods($institutionCode);  // 同步机构商品
            Goods::synGoodsGoodsCategory($institutionCode);  // 同步机构扩展分类

            Information::copyAdAndCategoryByInstCode($institutionCode); //同步机构广告信息
            Activity::sysBargain($applyData['parentCode'], $institutionCode); //同步机构活动

            // 创建机构管理员 待确定权限
            $password = rand(100000, 999999);
            $applyData['password'] = $password;
            $data = [
                'institution_code' => $institutionCode,
                'name' => $applyData['txtContacter'],
                'account' => $applyData['txtContacterPhone'],   //手机号码
                'password' => $password, //随机6位
                'phone' => $applyData['txtContacterPhone'],
                'is_enabled' => '1',
                'remark' => '',
                'role_list' => [
                    \Yii::$app->params['institution.admin.role.id']
                ]
            ];

            if (!(Manager::add($data) > 0)) {
                $message = '根据当前手机号生成管理员重复，请使用其他手机号申请';
                $transaction->rollBack();
                if ($institutionCode != '') {
                    Inteface::delInstitutionCode($institutionCode);
                }
                return false;
            }

            //保存创建机构记录
            $applyData['institution_code'] = $institutionCode;
            $applyData['create_manager_id'] = '';
            switch ($type) {
                case 'schr':
                case 'shmd':
                    $applyData['apply_for_info'] = [
                        '企业性质' => isset($applyData['txtType']) ? $applyData['txtType'] : '',
                        '企业行业' => isset($applyData['txtIndustry']) ? $applyData['txtIndustry'] : '',
                        '员工人数' => isset($applyData['txtWorkerCount']) ? $applyData['txtWorkerCount'] : '',
                        '注册资金' => isset($applyData['txtFund']) ? $applyData['txtFund'] : '',
                        '营业执照' => isset($applyData['txtLicense']) ? $applyData['txtLicense'] : '',
                        '部门职务' => isset($applyData['txtContacterJob']) ? $applyData['txtContacterJob'] : '',
                        '联系座机' => isset($applyData['txtTel']) ? $applyData['txtTel'] : '',
                        '联系邮箱' => isset($applyData['txtEmail']) ? $applyData['txtEmail'] : '',
                        '联系地址' => isset($applyData['txtAddress']) ? $applyData['txtAddress'] : ''
                    ];
                    break;
                case 'ylb':
                    $applyData['apply_for_info'] = [
                        '员工人数' => isset($applyData['txtWorkerCount']) ? $applyData['txtWorkerCount'] : '',
                        '营业执照' => isset($applyData['txtLicense']) ? $applyData['txtLicense'] : '',
                        '部门职务' => isset($applyData['txtContacterJob']) ? $applyData['txtContacterJob'] : '',
                        '联系座机' => isset($applyData['txtTel']) ? $applyData['txtTel'] : '',
                        '联系邮箱' => isset($applyData['txtEmail']) ? $applyData['txtEmail'] : '',
                        '联系地址' => isset($applyData['txtAddress']) ? $applyData['txtAddress'] : ''
                    ];
                    break;
                case 'hy':
                case 'xt':

                    $applyData['apply_for_info'] = [];
                    break;
            }

            $record_id = ApplyInstitution::save($applyData);
            if ($record_id != false) {
                $applyData['record_id'] = $record_id;
            }
            $transaction->commit();

            if ($institutionCode != null) {
                $host = \Yii::$app->request->hostInfo;
                $manage_url = $host;
                $mobile_url = $host . '/' . $institutionCode;
                $register_info = [$applyData['txtName'] . '积分商城', $manage_url, $applyData['txtContacterPhone'], $password];

                User::sendSms(80687, $applyData['txtContacterPhone'], $register_info);

                $other_info = [$applyData['txtName'] . '积分', $mobile_url];
                User::sendSms(80688, $applyData['txtContacterPhone'], $other_info);
            }
        } catch (\Exception $e) {
            $result = false;
            $transaction->rollBack();
            $message = $e->getMessage();
            if ($institutionCode != '') {
                Inteface::delInstitutionCode($institutionCode);
            }
        }
        return $result;
    }

    /**
     *如果是在微信里,此微信用户已经绑定过手机号的,就直接登录了。
     */
    public static function weixinAutoLogin()
    {
        //判断是否在微信内
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger")) {
            $currentUser = self::getCurrentUser();
            if ($currentUser == null) {
                $openid = self::getWeixinOpenid();
                if ($openid != null) {
                    try {
                        $user = User::getEnabledUserByWeixinOpenid(Mall::getCurrentInstitutionCode(), $openid);
                        if ($user != null) {
                            if (!empty($user['phone'])) {
                                //更新用户微信信息并登陆
                                $openid = Mall::getWeixinOpenid();
                                $nickname = Mall::getWeixinNickname();
                                $header = Mall::getWeixinHeader();
                                if ($user['header_url'] != $header || $user['name'] != $nickname) {
                                    $data = [
                                        'id' => $user['id'],
                                        'code' => $user['code'],
                                        'name' => $nickname,
                                        'institution_code' => Mall::getCurrentInstitutionCode(),
                                        'phone' => $user['phone'],
                                        'isEnabled' => $user['is_enabled'],
                                        'remark' => $user['remark'],
                                        'wx_openid' => $openid,
                                        'header_url' => $header
                                    ];
                                    $userId = User::addUser($data)['userId'];
                                    $user = User::getUser($userId);
                                }
                                Mall::setCurrentUser($user);
                            } else {
                                $phone = User::getUserPhoneByWxOpenid($openid);
                                if ($phone != null) {
                                    $openid = Mall::getWeixinOpenid();
                                    $nickname = Mall::getWeixinNickname();
                                    $header = Mall::getWeixinHeader();

                                    $data = [
                                        'id' => $user['id'],
                                        'code' => $user['code'],
                                        'name' => $nickname,
                                        'institution_code' => Mall::getCurrentInstitutionCode(),
                                        'phone' => $phone,
                                        'isEnabled' => $user['is_enabled'],
                                        'remark' => $user['remark'],
                                        'wx_openid' => $openid,
                                        'header_url' => $header
                                    ];
                                    $userId = User::addUser($data)['userId'];
                                    $user = User::getUser($userId);
                                    Mall::setCurrentUser($user);
                                }
                            }

                        }
                    } catch (\Exception $e) {
                    }
                }
            }


        }
    }
}